/**
 * Copyright (c) 2016-2019 九点科技 All rights reserved.
 *
 * https://www.9dyun.cn
 *
 * 版权所有，侵权必究！
 */

package com.dian.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.core.parser.ISqlParserFilter;
import com.baomidou.mybatisplus.core.parser.SqlParserHelper;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import com.dian.common.local.UserLocal;
import com.google.common.collect.Lists;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.regex.Pattern;

/**
 * mybatis-plus配置
 *
* @author  xiaolai@9dyun.cn
 */
@Configuration
public class MybatisPlusConfig {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    private static final String SYSTEM_ENT_ID = "tenant_id";
    private static final List<String> IGNORE_TENANT_TABLES = Lists.newArrayList(
            "ACT_.*",
            "sys_config",
            "sys_dist",
            "sys_user",
            "sys_user_role",
            "sys_menu",
            "sys_role_menu",
            "sys_ent",
            "schedule_job",
            "schedule_job_log",
            "sys_captcha",
            "sys_user_token",
            "sys_dept");
    @Bean
    public ISqlInjector sqlInjector() {
        return new LogicSqlInjector();
    }


    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new com.dian.common.handler.MyMetaObjectHandler();

    }
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();

        // SQL解析处理拦截：增加租户处理回调。
        TenantSqlParser tenantSqlParser = new TenantSqlParser()
                .setTenantHandler(new TenantHandler() {
                    @Override
                    public Expression getTenantId() {


                        // 从当前系统上下文中取出当前请求的服务商ID，通过解析器注入到SQL中。
                        /*
                        UserDto sysUserEntity=(UserDto) SecurityUtils.getSubject().getPrincipal();
                        Long currentProviderId = sysUserEntity.getEntId();
                        if (null == currentProviderId) {
                            throw new RuntimeException("#1129 getCurrentProviderId error.");
                        }
                        return new LongValue(currentProviderId);
                        */
                         return new LongValue(UserLocal.getTenantId());

                        //return new LongValue(tenantInfoService.getTenantId());
                    }

                    @Override
                    public String getTenantIdColumn() {
                        return SYSTEM_ENT_ID;
                    }

                    @Override
                    public boolean doTableFilter(String tableName) {
                        // 忽略掉一些表：如租户表（provider）本身不需要执行这样的处理。
                        return IGNORE_TENANT_TABLES.stream().anyMatch((e) ->
                                       Pattern.matches(e, tableName)
                         );
                    }
                });
        paginationInterceptor.setSqlParserList(Lists.newArrayList(tenantSqlParser));

        paginationInterceptor.setSqlParserFilter(new ISqlParserFilter() {
            @Override
            public boolean doFilter(MetaObject metaObject) {
                MappedStatement ms = SqlParserHelper.getMappedStatement(metaObject);
                // 过滤自定义查询此时无租户信息约束
                if ("com.dian.modules.sys.dao.SysUserDao.selectPage".equals(ms.getId())) {
                    return true;
                }
                return false;
            }
        });
        return paginationInterceptor;
    }

    @Bean(name = "performanceInterceptor")
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }
}
